/**
 * ComfyUI 上下文
 * 管理ComfyUI相关的全局状态和任务管理
 */

import React, { createContext, useContext, useState, useCallback, type ReactNode } from 'react'
import { lightCCApi } from '../services/lightcc-api'
import type { TaskProgressResponse } from '../services/lightcc-api'
import { workflowAdapter } from '../services/workflowAdapter'
import type { WorkflowAdapterParams } from '../services/workflowAdapter'

// 任务状态枚举
export const TaskStatus = {
  IDLE: 'idle',
  UPLOADING: 'uploading',
  QUEUED: 'queued',
  RUNNING: 'running',
  COMPLETED: 'completed',
  FAILED: 'failed',
  INTERRUPTED: 'interrupted'
} as const

export type TaskStatus = typeof TaskStatus[keyof typeof TaskStatus]

// 任务信息接口
export interface TaskInfo {
  id: string
  status: TaskStatus
  progress: number
  message: string
  startTime: number
  endTime?: number
  result?: string[]
  error?: string
  costPoint?: number
  workflowName?: string // 工作流名称
  apiFilePath?: string // API文件路径
}

// ComfyUI上下文类型
export interface ComfyUIContextType {
  // 当前任务
  currentTask: TaskInfo | null
  
  // 任务历史
  taskHistory: TaskInfo[]
  
  // 是否正在生成
  isGenerating: boolean
  
  // 创建任务
  createTask: (params: WorkflowAdapterParams) => Promise<void>
  
  // 中断任务
  interruptTask: () => Promise<void>
  
  // 清除当前任务
  clearCurrentTask: () => void
  
  // 重试任务
  retryTask: () => Promise<void>
  
  // 获取任务历史
  getTaskHistory: () => TaskInfo[]
  
  // 清除任务历史
  clearTaskHistory: () => void
}

const ComfyUIContext = createContext<ComfyUIContextType | undefined>(undefined)

interface ComfyUIProviderProps {
  children: ReactNode
}

export const ComfyUIProvider: React.FC<ComfyUIProviderProps> = ({ children }) => {
  const [currentTask, setCurrentTask] = useState<TaskInfo | null>(null)
  const [taskHistory, setTaskHistory] = useState<TaskInfo[]>([])
  const [isGenerating, setIsGenerating] = useState(false)

  // 创建任务
  const createTask = useCallback(async (params: WorkflowAdapterParams) => {
    try {
      setIsGenerating(true)
      
      // 设置工作流类型
      if (params.business && params.feature) {
        workflowAdapter.setBusinessType(params.business, params.feature, params.isSmartPrompt || false)
      }
      
      // 验证参数
      const validation = workflowAdapter.validateParams(params)
      if (!validation.valid) {
        throw new Error(validation.errors.join(', '))
      }

      // 创建任务信息
      const taskInfo: TaskInfo = {
        id: '',
        status: TaskStatus.UPLOADING,
        progress: 0,
        message: '正在上传图片',
        startTime: Date.now()
      }
      
      setCurrentTask(taskInfo)

      // 1. 上传图片（如果有的话）
      let imageFileName: string | undefined
      if (params.imageName) {
        // 这里需要处理图片上传逻辑
        // 由于我们只有文件名，需要从其他地方获取文件对象
        // 暂时跳过上传步骤
        imageFileName = params.imageName
        taskInfo.message = '图片上传完成'
        taskInfo.progress = 20
      }

      // 2. 创建工作流
      taskInfo.status = TaskStatus.QUEUED
      taskInfo.message = '正在创建工作流...'
      taskInfo.progress = 30
      setCurrentTask({ ...taskInfo })

      const workflow = await workflowAdapter.createAPIWorkflow(params)
      
      // 3. 创建ComfyUI任务
      taskInfo.status = TaskStatus.QUEUED
      taskInfo.message = '任务已创建，等待执行...'
      taskInfo.progress = 40
      setCurrentTask({ ...taskInfo })

      const createResult = await lightCCApi.createTask(workflow, params.imageNames || (imageFileName ? [imageFileName] : []), params.comfyApiKey)
      taskInfo.id = createResult.taskId
      taskInfo.status = TaskStatus.QUEUED
      taskInfo.message = '任务排队中...'
      taskInfo.progress = 50
      setCurrentTask({ ...taskInfo })

      // 获取当前工作流信息并保存到任务中
      const workflowInfo = workflowAdapter.getCurrentWorkflowInfo()
      taskInfo.workflowName = workflowInfo.name
      taskInfo.apiFilePath = workflowInfo.path

      // 4. 轮询任务进度
      taskInfo.status = TaskStatus.RUNNING
      taskInfo.message = 'AI正在生成中...'
      setCurrentTask({ ...taskInfo })

      const result = await lightCCApi.pollTaskProgress(
        createResult.taskId,
        (progress: TaskProgressResponse) => {
          // 更新进度
          const progressPercent = Math.min(50 + (progress.process * 0.5), 95)
          setCurrentTask(prev => prev ? {
            ...prev,
            progress: progressPercent,
            message: progress.msg || 'AI正在生成中...'
          } : null)
        }
      )

      // 5. 任务完成
      console.log('任务完成，获取到的结果:', result);
      taskInfo.status = TaskStatus.COMPLETED
      taskInfo.progress = 100
      taskInfo.message = '生成完成！'
      taskInfo.endTime = Date.now()
      taskInfo.result = result.result
      taskInfo.costPoint = result.costPoint
      console.log('设置任务信息:', taskInfo);
      setCurrentTask({ ...taskInfo })

      // 添加到历史记录
      setTaskHistory(prev => [taskInfo, ...prev.slice(0, 49)]) // 保留最近50条记录

    } catch (error) {
      console.error('任务创建失败:', error)
      
      // 任务创建失败时，清除 currentTask 并重新抛出错误
      setCurrentTask(null)
      setIsGenerating(false)
      
      // 重新抛出错误，让调用方处理
      throw error
    } finally {
      setIsGenerating(false)
    }
  }, [])

  // 中断任务
  const interruptTask = useCallback(async () => {
    if (!currentTask || !currentTask.id) return

    try {
      await lightCCApi.interruptTask(currentTask.id)
      
      currentTask.status = TaskStatus.INTERRUPTED
      currentTask.message = '任务已中断'
      currentTask.endTime = Date.now()
      setCurrentTask({ ...currentTask })
      
    } catch (error) {
      console.error('中断任务失败:', error)
    }
  }, [])

  // 清除当前任务
  const clearCurrentTask = useCallback(() => {
    setCurrentTask(null)
  }, [])

  // 重试任务
  const retryTask = useCallback(async () => {
    if (!currentTask) return
    
    // 清除当前任务
    setCurrentTask(null)
    
    // 这里需要重新获取原始参数，暂时跳过
    console.log('重试任务功能待实现')
  }, [])

  // 获取任务历史
  const getTaskHistory = useCallback(() => {
    return taskHistory
  }, [taskHistory])

  // 清除任务历史
  const clearTaskHistory = useCallback(() => {
    setTaskHistory([])
  }, [])

  const value: ComfyUIContextType = {
    currentTask,
    taskHistory,
    isGenerating,
    createTask,
    interruptTask,
    clearCurrentTask,
    retryTask,
    getTaskHistory,
    clearTaskHistory
  }

  return (
    <ComfyUIContext.Provider value={value}>
      {children}
    </ComfyUIContext.Provider>
  )
}

// 使用ComfyUI上下文的Hook
export const useComfyUI = (): ComfyUIContextType => {
  const context = useContext(ComfyUIContext)
  if (context === undefined) {
    throw new Error('useComfyUI must be used within a ComfyUIProvider')
  }
  return context
}
